import React, { useState, useEffect } from 'react';
import type { ConnectState } from '@/models/connect';
import { connect, history } from 'umi';
import {
  Button,
  Form,
  Input,
  Table,
  Badge,
  Row,
  Col,
  Modal,
  Space,
} from 'antd';
import type { ColumnsType } from 'antd/es/table';
import type { TableListItem, DataType, logType } from '../data';
import { getInitData, getLogData } from '../service';

const Dev: React.FC<TableListItem> = (props) => {
  const [form] = Form.useForm();
  const [isModalOpen, setIsModalOpen] = useState(false);
  const [selectedRowKeys, setSelectedRowKeys] = useState<React.Key[]>([]);
  const [searchValue, setSearchValue] = useState<SearchValueType>({});
  const [data, setData] = useState();
  const [count, setCount] = useState();
  const [currentIndex, setCurrentIndex] = useState(1);
  const [pageSize, setPageSize] = useState(10);
  const {
    menuslider,
    menuslider: { systemMenuBar },
  } = props;

  const init = async () => {
    const params = {
      caseName: '',
      appName: '',
      environmentId: props.value,
      pageDTO: {
        pageIndex: '1',
        pageSize: '10',
      },
    };
    getInitData(params).then((res) => {
      setData(res.records);
      setCount(res.total);
    });
  };

  useEffect(() => {
    init();
  }, []);

  const onFinish = async (values: any) => {
    setSearchValue(() => {
      return values;
    });
    setCurrentIndex(1);
    setPageSize(10);
    const params = {
      caseName: values.caseName,
      appName: values.appName,
      environmentId: props.value,
      pageDTO: {
        pageIndex: '1',
        pageSize: '10',
      },
    };
    getInitData(params).then((res) => {
      setData(res.records);
      setCount(res.total);
    });
  };

  const onReset = () => {
    form.resetFields();
  };

  const openLog = (row: any) => {
    setIsModalOpen(true);
    // const params = {
    //   caseId: row.caseId,
    //   environmentId: props.value,
    //   pageDTO: {
    //     pageIndex: '1',
    //     pageSize: '10',
    //   },
    // };
  };

  const handleCancel = () => {
    setIsModalOpen(false);
  };

  const columns: ColumnsType<DataType> = [
    {
      title: '序号',
      dataIndex: 'index',
      align: 'center',
      render: (text, rocord, index) => index + 1,
    },
    {
      title: '测试用例名称',
      dataIndex: 'caseName',
    },
    {
      title: '应用名称',
      dataIndex: 'appName',
    },
    {
      title: '创建人',
      dataIndex: 'createUserName',
    },
    {
      title: '执行进度',
      dataIndex: 'executionResultName',
    },
    {
      title: '已执行接口结果',
      dataIndex: 'executionStatus',
      render: (text) => {
        return text === 0 ? '成功' : '失败';
      },
    },
    {
      title: '操作',
      dataIndex: 'option',
      render: (_, row) => {
        return (
          <Space>
            <a
              style={{ color: 'rgb(50, 110, 255)' }}
              onClick={() => jumpTo(row)}
            >
              编辑
            </a>
            <a
              style={{ color: 'rgb(50, 110, 255)' }}
              onClick={() => openLog(row)}
            >
              执行日志
            </a>
          </Space>
        );
      },
    },
  ];

  const onSelectChange = (newSelectedRowKeys: React.Key[]) => {
    console.log('selectedRowKeys changed: ', newSelectedRowKeys);
    setSelectedRowKeys(newSelectedRowKeys);
  };

  const rowSelection = {
    selectedRowKeys,
    onChange: onSelectChange,
  };

  const logColumns: ColumnsType<logType> = [
    {
      title: '序号',
      dataIndex: 'index',
      align: 'center',
      render: (text, rocord, index) => index + 1,
    },
    {
      title: '执行时间',
      dataIndex: 'date',
    },
    {
      title: '执行接口信息',
      dataIndex: 'inform',
    },
    {
      title: '执行结果',
      dataIndex: 'result',
    },
  ];

  const logData: logType[] = [
    {
      date: '2024-01-01',
      inform: '新增待办接口',
      result: '失败,xx参数报错',
    },
    {
      date: '2024-01-01',
      inform: '新增待办接口',
      result: '失败,xx参数报错',
    },
    {
      date: '2024-01-01',
      inform: '新增待办接口',
      result: '失败,xx参数报错',
    },
    {
      date: '2024-01-01',
      inform: '新增待办接口',
      result: '失败,xx参数报错',
    },
  ];

  const menuClick = (path: any, id?: string) => {
    const menuNavBarCopy = JSON.parse(JSON.stringify(systemMenuBar));
    const index = menuNavBarCopy.findIndex((item: any) => item.path === path);
    if (index < 0) {
      let data = menuslider.staffInfoSource[0].children.filter(
        (item: any) => item.path === path,
      );
      props.dispatch({
        type: 'menuslider/saveSystemMenuBar',
        payload: [...menuNavBarCopy, ...data],
      });
    }
    const queryString = id ? `?id=${id}` : '';
    history.push(`${path}${queryString}`);
  };

  const jumpTo = (row: any) => {
    if (row) {
      menuClick('/automated/detail', row.caseId);
    } else {
      menuClick('/automated/detail');
    }
  };

  return (
    <div>
      <div className="custom-form">
        <Form form={form} name="dev-form" onFinish={onFinish} colon={false}>
          <Row>
            <Col span={8}>
              <Form.Item
                name="caseName"
                label="测试用例名称"
                className="custom-form-item"
              >
                <Input placeholder="请输入" />
              </Form.Item>
            </Col>
            <Col span={8}>
              <Form.Item
                name="appName"
                label="应用名称"
                className="custom-form-item"
              >
                <Input placeholder="请输入" />
              </Form.Item>
            </Col>
            <Button
              type="primary"
              htmlType="submit"
              style={{ marginRight: '8px' }}
            >
              查询
            </Button>
            <Button htmlType="button" onClick={onReset}>
              重置
            </Button>
          </Row>
        </Form>
      </div>
      <Button type="primary" style={{ margin: '16px 0' }} onClick={jumpTo}>
        新增
      </Button>
      <Button style={{ margin: '16px 8px 16px 8px' }}>删除</Button>
      {/* <Button>导出</Button> */}
      <Table
        columns={columns}
        dataSource={data}
        rowSelection={rowSelection}
        pagination={{
          showSizeChanger: true,
          showQuickJumper: true,
          total: count,
          current: currentIndex,
          pageSize,
          showTotal: (count) => `共 ${count} 条`,
          onChange: (page, pageSize) => {
            const params = {
              caseName: searchValue?.caseName,
              appName: searchValue?.appName,
              environmentId: props.value,
              pageDTO: {
                pageIndex: '1',
                pageSize: '10',
              },
            };
            setCurrentIndex(page);
            setPageSize(pageSize);
            getInitData(params).then((res) => {
              setData(res.records);
              setCount(res.total);
            });
          },
        }}
      />
      <Modal
        style={{ top: 80 }}
        title="执行日志"
        open={isModalOpen}
        width={1000}
        onCancel={handleCancel}
        footer={[
          <Button key="close" type="primary" onClick={handleCancel}>
            关闭
          </Button>,
        ]}
        // getContainer={() => containerRef.current || document.body}
      >
        <Table columns={logColumns} dataSource={logData} />
      </Modal>
    </div>
  );
};

export default connect(({ menuslider }: ConnectState) => ({
  menuslider: menuslider,
  systemMenuBar: menuslider.systemMenuBar,
}))(Dev);
